package com.qo.qsdk.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import androidx.core.content.SharedPreferencesCompat;

import com.google.gson.Gson;
import com.qo.qsdk.model.SDKInfoModel;
import com.qo.qsdk.model.UserModel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Pattern;

public class QSDKHelper {

    private static final String TAG = QSDKHelper.class.getSimpleName();
    private volatile static QSDKHelper INSTANCE;

    private SDKInfoModel mConfigureModel;

    private UserModel mUserModel;

    public void setConfigureModel(SDKInfoModel mConfigureModel) {
        this.mConfigureModel = mConfigureModel;
    }

    public SDKInfoModel getConfigureModel() {
        return mConfigureModel == null ? new SDKInfoModel() : mConfigureModel;
    }

    public void setUserModel(Activity activity, UserModel mUserModel) {
        if (mUserModel != null) {
            this.mUserModel = mUserModel;
            setItem(activity, UserModel.USER_KEY, new Gson().toJson(mUserModel));
        }else{
            this.mUserModel = new UserModel();
            delItem(activity, UserModel.USER_KEY);
        }
    }

    public UserModel getUserInfoModel(Activity activity) {
        if (mUserModel == null || mUserModel.getAccount().length() == 0) {
            String r = (String) getItem(activity, UserModel.USER_KEY,"");
            if (r != null && r.length() != 0 && r.startsWith("{") && r.endsWith("}")) {
                mUserModel = new Gson().fromJson(r,UserModel.class);
            }else{
                mUserModel = new UserModel();
            }
        }
        return mUserModel;
    }

    private static final String FILE_NAME = "QSDK_SHARE";
    public void setItem(Activity activity, String key, Object object) {
        if (activity == null) return;
        try {
            SharedPreferences sp = activity.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
            if (sp != null) {
                SharedPreferences.Editor editor = sp.edit();
                if (editor != null) {
                    if (object instanceof String)
                    {
                        editor.putString(key, (String) object);
                    } else if (object instanceof Integer)
                    {
                        editor.putInt(key, (Integer) object);
                    } else if (object instanceof Boolean)
                    {
                        editor.putBoolean(key, (Boolean) object);
                    } else if (object instanceof Float)
                    {
                        editor.putFloat(key, (Float) object);
                    } else if (object instanceof Long)
                    {
                        editor.putLong(key, (Long) object);
                    } else
                    {
                        editor.putString(key, object.toString());
                    }
                    editor.apply();
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Object getItem(Activity activity, String key, Object defaultObj) {
        try {
            if (activity != null) {
                SharedPreferences sp = activity.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
                if (sp != null) {
                    if (defaultObj instanceof String)
                    {
                        return sp.getString(key, (String) defaultObj);
                    } else if (defaultObj instanceof Integer)
                    {
                        return sp.getInt(key, (Integer) defaultObj);
                    } else if (defaultObj instanceof Boolean)
                    {
                        return sp.getBoolean(key, (Boolean) defaultObj);
                    } else if (defaultObj instanceof Float)
                    {
                        return sp.getFloat(key, (Float) defaultObj);
                    } else if (defaultObj instanceof Long)
                    {
                        return sp.getLong(key, (Long) defaultObj);
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

        if (defaultObj instanceof String)
        {
            return "";
        } else if (defaultObj instanceof Integer)
        {
            return 0;
        } else if (defaultObj instanceof Boolean)
        {
            return false;
        } else if (defaultObj instanceof Float)
        {
            return 0;
        } else if (defaultObj instanceof Long)
        {
            return 0;
        }

        return null;
    }

    public void delItem(Activity activity, String key) {
        if (activity == null) return;
        try {
            SharedPreferences sp = activity.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
            if (sp != null) {
                SharedPreferences.Editor editor = sp.edit();
                if (editor != null) {
                    editor.remove(key);
                    editor.apply();
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static QSDKHelper getInstance() {
        if (INSTANCE == null) {
            synchronized (QSDKHelper.class) {
                if (INSTANCE == null) {
                    INSTANCE = new QSDKHelper();
                }
            }
        }
        return INSTANCE;
    }

    public static boolean isAssertFileExists(Context context, String assetsFile) {
        try {
            InputStream stream = context.getAssets().open(assetsFile);
            return stream != null;
        } catch (IOException e) {
            // e.printStackTrace();
        }

        return false;
    }

    public static String getConfigure(Context context, String assetsFile) {

        if (!isAssertFileExists(context, assetsFile)) {
            return null;
        }

        InputStreamReader reader = null;
        BufferedReader br = null;
        try {
            reader = new InputStreamReader(context.getAssets().open(assetsFile));
            br = new BufferedReader(reader);

            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                    br = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (reader != null) {
                try {
                    reader.close();
                    reader = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;

    }

    public static int id(Context paramContext, String paramString) {
        return getIdentifier(paramContext, paramString, "id");
    }

    public static int string(Context paramContext, String paramString) {
        return getIdentifier(paramContext, paramString, "string");
    }

    public static int color(Context paramContext, String paramString) {
        return getIdentifier(paramContext, paramString, "color");
    }

    public static int mipmap(Context paramContext, String paramString) {
        return getIdentifier(paramContext, paramString, "mipmap");
    }

    public static int drawable(Context paramContext, String paramString) {
        return getIdentifier(paramContext, paramString, "drawable");
    }

    public static int layout(Context paramContext, String paramString) {
        return getIdentifier(paramContext, paramString, "layout");
    }

    public static int dimen(Context paramContext, String paramString) {
        return getIdentifier(paramContext, paramString, "dimen");
    }

    public static int style(Context paramContext, String paramString) {
        return getIdentifier(paramContext, paramString, "style");
    }

    public static int raw(Context paramContext, String paramString) {
        return getIdentifier(paramContext, paramString, "raw");
    }

    public static int anim(Context paramContext, String paramString) {
        return getIdentifier(paramContext, paramString, "anim");
    }

    public static int attr(Context context, String name) {
        return getIdentifier(context, name, "attr");
    }

    // 通过反射实现
    public static final int[] getStyleableIntArray(Context sContext, String name) {
        try {
            if (sContext == null)
                return null;
            Field field = Class.forName(sContext.getPackageName() + ".R$styleable").getDeclaredField(name);
            int[] ret = (int[]) field.get(null);
            return ret;
        } catch (Throwable t) {
        }
        return null;
    }

    public static final int getStyleableIntArrayIndex(Context sContext, String name) {
        try {
            if (sContext == null)
                return 0;
            // use reflection to access the resource class
            Field field = Class.forName(sContext.getPackageName() + ".R$styleable").getDeclaredField(name);
            int ret = (Integer) field.get(null);
            return ret;
        } catch (Throwable t) {
        }
        return 0;
    }

    public static int getColor(Context context, String str) {
        Resources resources = context.getResources();
        int id = color(context, str);

        if (id != 0) {
            return resources.getColor(id);
        }

        return 0;
    }

    public static Drawable getDrawable(Context context, String str) {
        Resources resources = context.getResources();
        int id = drawable(context, str);

        if (id != 0) {
            return resources.getDrawable(id);
        }

        return null;
    }

    public static String getString(Context context, String str) {
        Resources resources = context.getResources();
        int id = string(context, str);

        if (id != 0) {
            return resources.getString(id);
        }

        return null;
    }

    private static int getIdentifier(Context context, String name, String type) {
        Resources resources = context.getResources();
        String defPackage = context.getPackageName();
        int identifier = resources.getIdentifier(name, type, defPackage);
        return getIdentifier(name, type, identifier);
    }

    private static int getIdentifier(String name, String defType, int identifier) {
        if (identifier == 0) {
            Log.e(TAG, "#* EE: resource " + name + ", type " + defType + ", undefined.");
        }
        return identifier;
    }

    public static int dip2px(Context context, int dpValue) {
        DisplayMetrics displayMetrics = context.getApplicationContext().getResources().getDisplayMetrics();
        int i = displayMetrics.densityDpi;
        float f = i / 160.0F;
        return (int) (dpValue * f + 0.5F);
    }

    public String getAndroidId(Activity activity) {
        String androidId = Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
        if (androidId == null || androidId.length() == 0 || androidId.equals("9774d56d682e549c") || Pattern.matches("0{11,}", androidId)) {
            androidId = "";
//            Random random = new Random();
//            androidId = "a-" + Integer.toHexString(random.nextInt()) + Integer.toHexString(random.nextInt()) + Integer.toHexString(random.nextInt());
        }
        return androidId;
    }

    public interface GetAdidCallback {
        void onResult(String id);
    }

    public interface GetDeviceIdCallback {
        void onResult(String id);
    }

    public void getDeviceId(Activity activity, GetDeviceIdCallback callback) {
        String key = "qsdk_device_id";
        String deviceId = (String) getItem(activity, key, "");
        if (deviceId == null || deviceId.length() == 0) {
            getAdid(activity, new GetAdidCallback() {
                @Override
                public void onResult(String adid) {
                    if (adid.length() > 0) {
                        setItem(activity, key, adid);
                        if (callback != null) callback.onResult(adid);
                        return;
                    }
                    String androidId = getAndroidId(activity);
                    if (androidId.length() > 0) {
                        setItem(activity, key, androidId);
                        if (callback != null) callback.onResult(androidId);
                        return;
                    }
                    String tempAdid = "g-" + UUID.randomUUID().toString().toLowerCase();
                    setItem(activity, key, tempAdid);
                    if (callback != null) callback.onResult(tempAdid);
                }
            });
        }else{
            if (callback != null) callback.onResult(deviceId);
        }
    }

    public void getAdid(Activity activity, GetAdidCallback callback) {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        String adid = AdidClient.getGoogleAdId(activity);
                        if (adid == null) adid = "";
                        if (adid.equals("00000000-0000-0000-0000-000000000000")) adid = "";
//                        if (adid.length() == 0) adid = "g-" + UUID.randomUUID().toString().toLowerCase();
                        Log.e("aaa", adid);
                        if (callback != null) callback.onResult(adid);
                    } catch (Exception e) {
                        if (callback != null) callback.onResult("");
                    }
                }
            }).start();
        }catch (Exception e){
            if (callback != null) callback.onResult("");
        }
    }

    public static boolean isActivityFullScreen(Activity activity) {
        WindowManager.LayoutParams attrs = activity.getWindow().getAttributes();
        return (attrs.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
    }

    @SuppressWarnings("all")
    public static int statusBarHeight(Context context) {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object o = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = (Integer)field.get(o);
            return context.getResources().getDimensionPixelOffset(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    private static Handler mUIHandler = new Handler(Looper.getMainLooper());

    public static Handler getHandler() {
        return mUIHandler;
    }

    public static int getRealHight(Context context) {
        DisplayMetrics displayMetrics = null;
        if (displayMetrics == null) {
            displayMetrics = new DisplayMetrics();
            WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            windowManager.getDefaultDisplay().getRealMetrics(displayMetrics);
        }
        return displayMetrics.heightPixels;
    }
}
